# -*- coding: UTF-8 -*-
# @description : python
# @Author : zyl
# @Time : 2021/8/27 16:38
# @Remark:
from mxsoftpy import Server
from db.common.VideoManage.VideoMonitor.Group import GroupDB
from model.common.VideoManage.VideoMonitor.Group import GroupModel
#from utils.public.data_process import list_to_trees
from mxsoftpy.exception import DataError


class GroupServer(Server):
    """
    视频监控组
    """
    __model__ = GroupModel
    __db__ = GroupDB

    def CheckGroupLevel(self, GroupId):
        """
        检查组目录层级
        :param GroupId:  父ID
        :return:
        """
        group_dict = self.db.group_dict()
        group_dict = sorted(group_dict.items(), key=lambda k: int(k[0]), reverse=False)
        res = dict()
        for v in group_dict:
            res[v[0]] = {'id': v[0], 'name': v[1]['GroupName'], 'parent': v[1]['parent']}
        for d_id, d_dic in res.items():
            pid = d_dic.get('parent')
            if not pid or pid == "0":
                d_dic['level'] = 0
            else:
                d_dic['level'] = res[pid]['level'] + 1
        if res[GroupId]['level'] >= 5:
            raise Exception('目录层级已超过最大')

    def create(self, *args, **kwargs):
        """
        新增视频监控组信息
        :param args:
        :param kwargs:
        :return:
        """
        self.CheckGroupLevel(kwargs['parent'])
        return self.db.create(*args, **kwargs)

    def list_to_trees(self, data, parent_column="parent_code", child_column="children", current_column=None,
                      current_path=None):
        """
        将数据转换为树结构
        :param data: 数据字典
                    eg:
                        {"1": {"name": "测试视频组", "parent_code": 0},
                         "2": {"name": "测试视频组", "parent_code": 1},
                         "3": {"name": "测试视频组", "parent_code": 0},
                         "4": {"name": "测试视频组", "parent_code": 1},
                         "5": {"name": "测试视频组", "parent_code": 1},
                         "6": {"name": "测试视频组", "parent_code": 5}}
        :param parent_column: 父ID字段名，父ID默认为0
        :param child_column: 子列表字典名称
        :param current_column: 当前展开值字段名，若找到展开值增加["open"] = "1"
        :param current_path: 当前展开值
        :return: 树结构
        """

        data_tree_list = []  # 整个数据大列表
        for d_id, d_dic in data.items():
            pid = d_dic.get(parent_column)  # 取每一个字典中的父id
            if not pid or pid == "0":  # 父id=0，就直接加入数据大列表
                d_dic['level'] = 0
                data_tree_list.append(d_dic)
            else:  # 父id>0 就加入父id队对应的那个的节点列表
                try:  # 判断异常代表有子节点，增加子节点列表=[]
                    d_dic['level'] = data[pid]['level'] + 1
                    data[pid][child_column].append(d_dic)
                except KeyError:
                    data[pid][child_column] = []
                    data[pid][child_column].append(d_dic)

            # 展开节点
            if current_path:
                if current_path == d_dic.get(current_column):
                    d_dic["open"] = "1"
                    while pid and pid != "0":
                        data[pid]["open"] = "1"
                        pid = data[pid][parent_column]
        return data_tree_list

    def list(self, **kwargs):
        """
        获取视频组列表
        """
        group_dict = self.db.group_dict(**kwargs)
        res = dict()
        if 'GroupName' in kwargs:
            Groups = list()
            for k, v in group_dict.items():
                Groups.append({'id': k, 'name': v['GroupName'], 'parent': v['parent']})
            return Groups
        group_dict = sorted(group_dict.items(), key=lambda k: int(k[0]), reverse=False)

        for v in group_dict:
            res[v[0]] = {'id': v[0], 'name': v[1]['GroupName'], 'parent': v[1]['parent']}
        try:
            tree = self.list_to_trees(res, 'parent')
        except KeyError:
            raise DataError('数据异常，无法生成视频组节点树')
        return tree

    def delete(self, **kwargs):
        """
        删除视频监控组
        :param kwargs:
        :return:
        """
        return self.db.delete(kwargs['id'])

    def update(self, **kwargs):
        """
        修改视频监控组名称
        :param kwargs:
        :return:
        """
        return self.db.update(kwargs['id'], **kwargs)
